package skylineUB10;

public class Line {
	
	Point p1 = null;
	Point p2 = null;
	
	Line(Point p1, Point p2) {
		this.p1 = p1;
		this.p2 = p2;
	}
	
	
	/**
	 * intersects two lines
	 */
	static Point intersect(Line l1, Line l2) {
		double x = 0, y = 0, m1 = 0, m2 = 0;
		
		if ((l1.p2.x - l1.p1.x) == 0) {
			// line one is parallel to y-axis
			if ((l2.p2.x - l2.p1.x) == 0) {
				// other line too :-) => parallels
				return null;
			}
			m2 = (l2.p2.y - l2.p1.y) / (l2.p2.x - l2.p1.x);
			x = l1.p1.x;
			y = (m2 * x) + (l2.p1.y - (m2 * l2.p1.x));
		} else 	if ((l2.p2.x - l2.p1.x) == 0) {
			// line two is parallel to y-axis
			// first line is not parallel to y-axis
			m1 = (l1.p2.y - l1.p1.y) / (l1.p2.x - l1.p1.x);
			x = l2.p1.x;
			y = (m1 * x) + (l1.p1.y - (m1 * l1.p1.x));			
		} else {
			m1 = (l1.p2.y - l1.p1.y) / (l1.p2.x - l1.p1.x);
			m2 = (l2.p2.y - l2.p1.y) / (l2.p2.x - l2.p1.x);
			if (m1 == m2) {
				// parallel lines
				return null;
			}
			x = ((l2.p1.y - l1.p1.y) - (m2 * l2.p1.x - m1* l1.p1.x)) / (m1 - m2);
			y = (m1 * x) + (l1.p1.y - (m1 * l1.p1.x));
		}
		
		// check if p is on both lines
		double small = 0, bigger = 0, temp = 0;
		
		small = l1.p1.x;
		bigger = l1.p2.x;
		if (bigger < small) {
			temp = bigger;
			bigger = small;
			small = temp;
		}
		if (!((small <= x) && (x <= bigger))) return null;
		
		small = l2.p1.x;
		bigger = l2.p2.x;
		if (bigger < small) {
			temp = bigger;
			bigger = small;
			small = temp;
		}
		if (!((small <= x) && (x <= bigger))) return null;
		
		// return point
		return new Point(x,y);
	}
	
	
}
